#include <stdio.h>
#include "ThreadPool.h"
#include <unistd.h>
#include <stdbool.h>
#include <assert.h>
#include <pthread.h>
#include <time.h>
#include <stdlib.h>
#include <string.h>
const int g_producer_num=3;

void Print(void *args)
{
    char* str=(char *)args;

    fprintf(stdout,str);
    fprintf(stdout,"%d\n",(int)pthread_self());

}

/*
    开始生产任务很快--->增加线程
    之后生产任务很慢--->减少线程
*/

void *producer(void *args)
{
    assert(args!=NULL);
    ThreadPool *threadPoolPtr=(ThreadPool *)args;

    Task *taskPtr=(Task *)malloc(sizeof(struct Task));
    assert(taskPtr!=NULL);
    (void*)taskPtr;

    //Task task;

    int i=0;

    while(true)
    {
        // 生产任务
        taskPtr->function=Print;

        char *buff=(char *)malloc(sizeof(char)*64);

        memset(buff,0,64);

        strcat(buff,"任务---");

        taskPtr->args=(void *)buff;
        //sleep(1);
        if(i++<6)
        {
            usleep(9999);
        }
        else
        {
            sleep(15);

            // 推送任务---测试线程池的销毁
            printf("推送任务:%d\n",(int)pthread_self());
            ThreadPool_PushTask(threadPoolPtr,taskPtr);
            pthread_exit(NULL);
        }

        // 推送任务
        printf("推送任务:%d\n",(int)pthread_self());
        ThreadPool_PushTask(threadPoolPtr,taskPtr);
    }

}

int main(/* int,char**,char** */)
{
    //srand((unsigned int)time(NULL));

    ThreadPool *threadPoolPtr=ThreadPool_Create(3,9,99);

    fprintf(stdout,"启动成功 : %p\n",threadPoolPtr);

    pthread_t tids[g_producer_num];

    int i=0;
    for(i=0;i<g_producer_num;++i)
    {
        pthread_create(tids+i,NULL,producer,(void *)threadPoolPtr);
    }

    for(i=0;i<g_producer_num;++i)
    {
        pthread_join(tids[i],NULL);
    }

    printf("ThreadPool_Destroy strat\n");
    ThreadPool_Destroy(threadPoolPtr);
    printf("ThreadPool_Destroy success\n");

    return 0;
}